package com.kuaiditu.assistant.ui.login;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.kuaiditu.assistant.R;
import com.kuaiditu.assistant.api.assistant_api.AssistantApi;
import com.kuaiditu.assistant.api.assistant_api.base.AssistantResponse;
import com.kuaiditu.assistant.base.BaseActivity;
import com.kuaiditu.assistant.entity.AssistantUser;
import com.kuaiditu.assistant.module.retrofit.ProgressSubscriber;
import com.kuaiditu.assistant.ui.RegisterActivity;
import com.kuaiditu.assistant.ui.main.MainActivity;
import com.kuaiditu.assistant.util.LogUtil;
import com.kuaiditu.assistant.util.RxCountDown;
import com.kuaiditu.assistant.util.ToastUtil;
import com.kuaiditu.assistant.view.topbar.TopBar;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.observers.DefaultObserver;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DefaultSubscriber;

@Route(path = LoginActivity.PATH)
public class LoginActivity extends BaseActivity {
    public static final String PATH = "/user/login";
    public static final int REQ_CODE_REGISTER = 1001;

    @BindView(R.id.edit_mobile)
    EditText editMobile;
    @BindView(R.id.edit_sms_code)
    EditText editSmsCode;
    @BindView(R.id.tv_send_sms_code)
    TextView tvSendSmsCode;
    @BindView(R.id.btn_login)
    Button btnLogin;
    private TopBar mTopBar;


    private AssistantApi mAssistantApi;

    @Override
    public int initContentView() {
        return R.layout.activity_login;
    }

    @Override
    public void initInjector() {
        mAssistantApi = getApplicationComponent().getApiManager().getAssistantApi();
    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mTopBar = (TopBar) findViewById(R.id.top_bar);
        mTopBar.bind(this, true);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("注册").setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (requestCode == REQ_CODE_REGISTER && resultCode == Activity.RESULT_OK) {

            String mobile = data.getStringExtra("mobile");
            editMobile.setText(mobile);
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getTitle().equals("注册")) {
            ARouter.getInstance()
                    .build(RegisterActivity.PATH).navigation(this, REQ_CODE_REGISTER);
//            startActivity(new Intent(mContext, RegisterActivity.class));
        }
        return super.onOptionsItemSelected(item);
    }


    @OnClick(R.id.tv_send_sms_code)
    public void onTvSendSmsCodeClicked(View v) {
        String mobile = editMobile.getText().toString();
        if (TextUtils.isEmpty(mobile)) {
            ToastUtil.showToast("手机号不能为空");
            return;
        }
        sendSmsCode((TextView) v, mobile);
    }

    @OnClick(R.id.btn_login)
    public void onBtnLoginClicked() {
        String mobile = editMobile.getText().toString();
        String ramdon = editSmsCode.getText().toString();
        if (TextUtils.isEmpty(mobile)) {
            ToastUtil.showToast("手机号不能为空");
            return;
        }
        if (TextUtils.isEmpty(ramdon)) {
            ToastUtil.showToast("验证码不能为空");
            return;
        }
        login(mobile, ramdon);
    }


    private void countTime() {
        LogUtil.e("here time");
        Flowable.timer(60, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultSubscriber<Long>() {
                    @Override
                    public void onNext(Long t) {
                        tvSendSmsCode.setText(String.format("%sS", t));

                    }

                    @Override
                    public void onError(Throwable t) {
                        t.printStackTrace();
                    }

                    @Override
                    public void onComplete() {
                        tvSendSmsCode.setText("获取验证码");
                    }
                });
    }


    private void login(String mobile, String ramdon) {
        mAssistantApi.login(mobile, ramdon)
                .subscribe(new ProgressSubscriber<AssistantUser>(mContext) {
                    @Override
                    public void onNext(AssistantUser assistantUser) {
                        ARouter.getInstance().build(MainActivity.PATH).navigation();
                        finish();
                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }


    private void sendSmsCode(final TextView v, String mobile) {

        mAssistantApi.sendSmsCode(mobile,AssistantApi.ACTION_LOGIN)
                .subscribe(new ProgressSubscriber<AssistantResponse>(mContext) {
                    @Override
                    public void onNext(AssistantResponse assistantResponse) {
                        ToastUtil.showToast("短信发送成功");
                        v.setEnabled(false);
                        new RxCountDown()
                                .countdown(60)
                                .subscribe(new DefaultObserver<Integer>() {
                                    @Override
                                    public void onNext(@NonNull Integer integer) {
                                        v.setText(String.format("%ss", integer));
                                    }

                                    @Override
                                    public void onError(@NonNull Throwable e) {
                                        e.getMessage();
                                    }

                                    @Override
                                    public void onComplete() {
                                        v.setText("点击获取验证码");
                                        v.setEnabled(true);
                                    }
                                });
                    }

                    @Override
                    public void onFinish() {

                    }

                });


    }


}
